﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ZHDJ.JoinParty.BLL;
using FineUI;
using ZHDJ.Data.Models.JoinParty;
using System.Data;
using ZHDJ.Core.Util;
using ZHDJ.WebPage;

namespace JoinParty.admin.FlowStep
{
    public partial class SubActivistInvestigate : PageBase
    {
        private const int ResumeNum = 5;//填写简历数目
        public string ID
        {
            get
            {
                return GetQueryIntValue("id");
            }
        }
        #region ViewPower

        /// <summary>
        /// 本页面的浏览权限，空字符串表示本页面不受权限控制
        /// </summary>
        public override string ViewPower
        {
            get
            {
                return "";
            }
        }

        #endregion
        #region Page_Load

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindData();
                LoadData();
            }
            var ps = DB.PartyJoinProcesss.Find(this.CurrentStepID);
            this.lbWorkGuide.Text = ps.WorkPoint ?? "";
        }

        private void BindData()
        {
        }
        private void LoadData(string IsSave = "")
        {
            btnClose.OnClientClick = ActiveWindow.GetHideReference();

            #region 加载人员信息数据
            var app = DB.PartyJoinApplycation.Find(this.AppllicationID);
            var om = DB.PartyOrgMembers.Find(app.LoginID);
            var Contact = DB.partyJoinContacta.Where(a => a.AppllicationID == this.AppllicationID && a.ContactType == 0).ToList();

            this.txtUserName.Text = om.UserName;
            this.ddlGender.SelectedValue = om.Gender;
            this.ddlEducation.Text = om.Educational;
            this.txtNation.Text = om.Nation;
            this.txtNativePlace.Text = om.NativePlace;
            this.txtAdress.Text = om.Address;
            this.txtBirthplace.Text = om.Birthplace;
            this.txtTitle.Text = om.Title;
            this.txtExpertise.Text = om.Expertise;
            if (!string.IsNullOrEmpty(Convert.ToString(om.Birthday)))
            {
                this.dpBirthday.Text = om.Birthday?.ToString("yyyy-MM");
            }
            if (Convert.ToString(om.ImageUrl) != "")
            {
                imgPhoto.ImageUrl = UpFileBusiness.GetFileUrl(om.ImageUrl);

                PageContext.RegisterStartupScript("ReDoLayout();");

            }
            this.dpApplyTime.Text = PartyJoinApplycation.GetApplyTimeByLoginID(om.LoginID);
            if (Contact != null)
            {
                var CulturePeople = "";
                foreach (var item in Contact)
                {
                    CulturePeople += item.ContactName + "、";
                }
                this.txtCulturePeople.Text = CulturePeople.Substring(0, CulturePeople.Length - 1);
            }
            #endregion
            string activistsId = partyJoinPartyActivists.GetActivistsIDByStandID(this.CurrentStandID);
            if (!string.IsNullOrEmpty(activistsId))
            {
                this.hdfActivistsID.Value = activistsId;
                var oModel = DB.partyJoinPartyActivistss.Find(activistsId);
                this.txtFamily.Text = oModel.Family;
                this.txtSociology.Text = oModel.Sociology;
                this.txtWhereAndWhereReward.Text = oModel.WhereAndWhereReward;
                this.txtWhereAndWhereParty.Text = oModel.WhereAndWhereParty;
                this.txtCulturalRevolution.Text = oModel.CulturalRevolution;
                this.txtFormerName.Text = oModel.FormerName;
                this.txtFamilyOrigin.Text = oModel.FamilyOrigin;
                this.txtPersonalConstituent.Text = oModel.PersonalConstituent;
                this.txtPresentOccupation.Text = oModel.PresentOccupation;

                this.dpCultureTime.Text = oModel.CultureTime?.ToString("yyyy-MM-dd");
                if (!string.IsNullOrEmpty(Convert.ToString(oModel.JoinTheYouthLeagueTime)))
                {
                    this.dpJoinTheYouthLeagueTime.Text = string.Format("{0:yyyy-MM}", oModel.JoinTheYouthLeagueTime);
                }
                if (!string.IsNullOrEmpty(Convert.ToString(oModel.WorkTime)))
                {
                    this.dpWorkTime.Text = string.Format("{0:yyyy-MM}", oModel.WorkTime);
                }
                if (!string.IsNullOrEmpty(Convert.ToString(oModel.ConfirmActivistsTime)))
                {
                    this.dpConfirmActivistsTime.Text = string.Format("{0:yyyy-MM-dd}", oModel.ConfirmActivistsTime);
                }


            }
            else
            {
                dpConfirmActivistsTime.Text = DateTime.Now.ToString("yyyy-MM-dd");
            }
            LoadRptData(activistsId);
            //页面只读显示
            if (this.ReadOnly.Trim() == "1")
            {
                this.btnSubmit.Hidden = true;
                this.btnSaveClose.Hidden = true;
                if (IsJoinPartyAdmin)
                { this.btnSaveClose.Hidden = false; }
            }
        }
        /// <summary>
        /// 加载简历与培养联系人
        /// </summary>
        /// <param name="ActivistsID">积极份子ID</param>
        private void LoadRptData(string ActivistsID)
        {
            DataSet ResumeData = PartyJoinProbationaryResume.GetGridData(ActivistsID);
            if (ResumeData != null && ResumeData.Tables.Count > 0)
            {
                int addRowNum = ResumeNum - ResumeData.Tables[0].Rows.Count;
                for (int i = 0; i < addRowNum; i++)
                {
                    ResumeData.Tables[0].Rows.Add(ResumeData.Tables[0].NewRow());
                }
            }
            this.rptResumeData.DataSource = ResumeData;
            this.rptResumeData.DataBind();


            var standMode = DB.PartyJoinLinkExamples.Find(this.CurrentStandID);
            DataSet ContactData = partyJoinContact.GetGridData(standMode.AppllicationID, 0);
            int ContactsNum = 2;//标题占用的行数
            if (ContactData != null && ContactData.Tables.Count > 0)
            {
                ContactsNum = ContactsNum + ContactData.Tables[0].Rows.Count;
            }
            this.TDCultivatingContacts.RowSpan = ContactsNum;

            this.rptContactData.DataSource = ContactData;
            this.rptContactData.DataBind();
            if (ContactData.Tables[0].Rows.Count < 1)
            {
                this.TrContacts.Visible = false;
            }
        }

        /// <summary>
        /// 保存简历信息
        /// </summary>
        private void SaveRptData(string ActivistsID)
        {
            if (!string.IsNullOrEmpty(ActivistsID))
                PartyJoinProbationaryResume.DeleteResumeData(ActivistsID);
            for (int i = 0; i < 5; i++)
            {
                var StartTime = Request.Form["cPanel$rptResumeData$ctl0" + i + "$txtStartTime"];
                var EndTime = Request.Form["cPanel$rptResumeData$ctl0" + i + "$txtEndTime"];
                var Where = Request.Form["cPanel$rptResumeData$ctl0" + i + "$txtWhere"];
                var Witness = Request.Form["cPanel$rptResumeData$ctl0" + i + "$txtWitness"];
                if (!string.IsNullOrEmpty(StartTime) || !string.IsNullOrEmpty(EndTime) || !string.IsNullOrEmpty(Where) || !string.IsNullOrEmpty(Witness))
                {
                    PartyJoinProbationaryResume oModel = new PartyJoinProbationaryResume();
                    oModel.ID = StringHelper.NewID;
                    oModel.ActivistsID = ActivistsID;
                    oModel.StartTime = StartTime;
                    oModel.EndTime = EndTime;
                    oModel.Where = Where;
                    oModel.Witness = Witness;
                    oModel.OrderNo = i;
                    DB.PartyJoinProbationaryResumes.Add(oModel);
                    DB.SaveChanges();
                }
                else
                    break;
            }
        }

        private void SaveData(bool IsSaveLink)
        {
            string Message = "";///接收处理流程反馈的消息主要判断当前步骤是否已审核过
            bool bResult = false;

            if (string.IsNullOrEmpty(this.dpConfirmActivistsTime.Text.Trim()))
            {
                this.ClientScript.RegisterStartupScript(this.GetType(), "kk", "<script>alert('党组织确定为入党积极分子的时间不能为空！')</script>");
                return;
            }
            string ActivistsID = this.hdfActivistsID.Value.Trim();
            partyJoinPartyActivists PaInfo = new partyJoinPartyActivists();
            if (!string.IsNullOrEmpty(ActivistsID))
            {
                PaInfo = DB.partyJoinPartyActivistss.Find(ActivistsID);
            }
            PaInfo.Family = this.txtFamily.Text.Trim();
            PaInfo.Sociology = this.txtSociology.Text.Trim();
            PaInfo.WhereAndWhereReward = this.txtWhereAndWhereReward.Text.Trim();
            PaInfo.WhereAndWhereParty = this.txtWhereAndWhereParty.Text.Trim();
            PaInfo.CulturalRevolution = this.txtCulturalRevolution.Text.Trim();
            PaInfo.FormerName = this.txtFormerName.Text.Trim();
            PaInfo.FamilyOrigin = this.txtFamilyOrigin.Text.Trim();
            PaInfo.PersonalConstituent = this.txtPersonalConstituent.Text.Trim();
            PaInfo.PresentOccupation = this.txtPresentOccupation.Text.Trim();

            if (!string.IsNullOrEmpty(this.dpCultureTime.Text))
            {
                try
                {
                    PaInfo.CultureTime = Convert.ToDateTime(this.dpCultureTime.Text.Trim());
                }
                catch (Exception e)
                {
                    Alert.Show("您输入的培养对象时间是非法的时间格式，请重新输入！", String.Empty, ActiveWindow.GetHideReference());
                    return;
                }
            }

            if (!string.IsNullOrEmpty(this.dpJoinTheYouthLeagueTime.Text))
            {
                try
                {
                    PaInfo.JoinTheYouthLeagueTime = Convert.ToDateTime(this.dpJoinTheYouthLeagueTime.Text.Trim());
                }
                catch (Exception e)
                {
                    Alert.Show("您输入的入团时间是非法的时间格式，请重新输入！", String.Empty, ActiveWindow.GetHideReference());
                    return;
                }
            }
            if (!string.IsNullOrEmpty(this.dpWorkTime.Text))
            {
                try
                {
                    PaInfo.WorkTime = Convert.ToDateTime(this.dpWorkTime.Text.Trim());
                }
                catch (Exception e)
                {
                    Alert.Show("您输入的参加工作时间是非法的时间格式，请重新输入！", String.Empty, ActiveWindow.GetHideReference());
                    return;
                }
            }
            if (!string.IsNullOrEmpty(this.dpConfirmActivistsTime.Text.Trim()))
            {
                try
                {
                    PaInfo.ConfirmActivistsTime = Convert.ToDateTime(this.dpConfirmActivistsTime.Text.Trim());
                }
                catch (Exception e)
                {
                    Alert.Show("您输入的党组织确定为入党积极分子的时间是非法的时间格式，请重新输入！", String.Empty, ActiveWindow.GetHideReference());
                    return;
                }
            }

            if (!string.IsNullOrEmpty(ActivistsID))
            {
                bResult = DB.SaveChanges() > 0;
            }
            else
            {
                PaInfo.StandID = this.CurrentStandID;
                PaInfo.LoginID = this.CurrentUser.LoginID;
                PaInfo.ActivistsID = StringHelper.NewID;
                this.hdfActivistsID.Value = PaInfo.ActivistsID;
                PaInfo.CreateTime = DateTime.Now;
                DB.partyJoinPartyActivistss.Add(PaInfo);
                bResult = DB.SaveChanges() > 0;
            }

            if (bResult)
            {
                var app2 = DB.PartyJoinApplycation.Find(this.AppllicationID);
                var om = DB.PartyOrgMembers.Find(app2.LoginID);
                om.Title = this.txtTitle.Text;
                om.Birthplace = this.txtBirthplace.Text;
                om.Expertise = this.txtExpertise.Text;
                DB.SaveChanges();
                SaveRptData(PaInfo.ActivistsID);//保存简历信息
                if (IsSaveLink)//保存按钮不保存流程信息
                {
                    //保存流程信息                    
                    var oModelEx = DB.PartyJoinLinkExamples.Find(this.CurrentStandID);
                    oModelEx.Remark = string.Format("{0}录入入党积极分子考察表！", this.CurrentUser.UserName);
                    oModelEx.HandleUserID = this.CurrentUser.LoginID;
                    oModelEx.HandleUserName = this.CurrentUser.UserName;
                    oModelEx.HandleTime = DateTime.Now;
                    oModelEx.Status = (int)Enum_FlowStanceStatus.通过;


                    bResult = ProcesUtil.ApprovalProcesStep(oModelEx, out Message);
                    //if (bResult)
                    //{
                    //    #region 新增3条考察意见数据
                    //    for (int i = 0; i < 3; i++)
                    //    {
                    //        var example = DB.PartyJoinLinkExamples.Find(Convert.ToString(HttpContext.Current.Session["NextStandID"]));
                    //        PartyJoinApplycation app = ProcesUtil.GetApplycation(example.AppllicationID);

                    //        PartyJoinReviewOption rep = new PartyJoinReviewOption();
                    //        rep.ID = StringHelper.NewID;
                    //        rep.StandID = Convert.ToString(HttpContext.Current.Session["NextStandID"]);
                    //        rep.LoginID = app.LoginID;
                    //        rep.LoginName = app.UserName;
                    //        rep.OptionTime = DateTime.Now.AddMonths(i * 6);
                    //        rep.CreateTime = DateTime.Now;
                    //        DB.PartyJoinReviewOptions.Add(rep);

                    //        bResult = DB.SaveChanges() > 0;
                    //    }
                    //    HttpContext.Current.Session["NextStandID"] = null;
                    //    #endregion
                    //}
                }
                else
                {
                    Alert.Show("保存成功！", String.Empty, ActiveWindow.GetHideReference());
                }
            }
            if (!string.IsNullOrEmpty(Message))
                Alert.Show(Message, String.Empty, ActiveWindow.GetHideReference());

        }


        #endregion

        #region
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            this.SaveData(true);
            Alert.Show("提交成功！", String.Empty, ActiveWindow.GetHideReference());
            PageContext.RegisterStartupScript(ActiveWindow.GetHidePostBackReference());
            this.btnSaveClose.Hidden = true;
            this.btnSubmit.Hidden = true;
        }

        protected void btnSaveClose_Click(object sender, EventArgs e)
        {
            SaveData(false);
            Alert.Show("保存成功！", String.Empty, ActiveWindow.GetHideReference());
            PageContext.RegisterStartupScript(ActiveWindow.GetHidePostBackReference());
        }
        #endregion
    }
}